package cn.edu.zafu.bigdata.zyf;

import java.io.*;
import java.net.*;

public class Server {
    public static void main(String[] args) {
        int port = 1234; // 服务端监听的端口
        try (ServerSocket serverSocket = new ServerSocket(port)) {
            System.out.println("Server is running and waiting for client connection...");

            // 服务器无限循环，等待客户端连接
            while (true) {
                Socket socket = serverSocket.accept();
                System.out.println("Client connected.");

                // 处理客户端请求
                handleRequest(socket);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void handleRequest(Socket socket) {
        try (BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
             PrintWriter out = new PrintWriter(socket.getOutputStream(), true)) {

            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                System.out.println("Client says: " + inputLine);
                out.println("Server reply: " + inputLine); // 回复客户端发送的消息
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
